<template>
  <el-select
    v-model="selectedSite"
    placeholder="请选择站点"
    clearable
    filterable
    @change="handleChange"
    :loading="loading"
  >
    <el-option
      v-for="site in siteList"
      :key="site.id"
      :label="site.name"
      :value="site.id"
    >
      <span style="float: left">{{ site.name }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">
        {{ site.domain }}
      </span>
    </el-option>
  </el-select>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface Site {
  id: number
  name: string
  domain: string
  status: number
}

interface Props {
  modelValue?: number | null
  placeholder?: string
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择站点'
})

const emit = defineEmits<{
  'update:modelValue': [value: number | null]
  'change': [value: number | null]
}>()

// 响应式数据
const selectedSite = ref<number | null>(props.modelValue || null)
const siteList = ref<Site[]>([])
const loading = ref(false)

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  selectedSite.value = newValue || null
})

// 获取站点列表
const getSiteList = async () => {
  loading.value = true
  try {
    // TODO: 调用真实的站点API
    // const response = await siteApi.getList()
    // if (response.code === 0) {
    //   siteList.value = response.data
    // }
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    siteList.value = [
      { id: 1, name: '主站', domain: 'www.example.com', status: 1 },
      { id: 2, name: '移动站', domain: 'm.example.com', status: 1 },
      { id: 3, name: '测试站', domain: 'test.example.com', status: 1 }
    ]
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleChange = (value: number | null) => {
  selectedSite.value = value
  emit('update:modelValue', value)
  emit('change', value)
}

// 组件挂载时获取站点列表
onMounted(() => {
  getSiteList()
})
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
